import os
import random
import time
from Common.basepage import BasePage
from PageLocators.PlayerPage_locator import PlayerPageLocator as loc
from Common.connect_to_device import *
from Common.handle_log import do_log
from PageObjects.Main_page import MainPage

def time_to_seconds(time_str):
    """Convert a time string in the format HH:MM:SS to total seconds."""
    h, m, s = map(int, time_str.split(':'))
    return h * 3600 + m * 60 + s


def seconds_to_time(seconds):
    """Convert total seconds to a time string in the format HH:MM:SS."""
    h = seconds // 3600
    m = (seconds % 3600) // 60
    s = seconds % 60
    return f"{int(h):02}:{int(m):02}:{int(s):02}"


class PlayerPage(BasePage):


    def click_previous(self):
        self.click_element(loc.previous_loc, "播放器页面_点击上一集")
    def click_center(self):
        self.click_point(0.5, 0.5, "点击屏幕中心")

    def click_next(self):
        self.click_element(loc.next_loc, "播放器页面_点击下一集")

    def click_play(self):
        """点击播放器页面，暂停播放"""
        if not self.judge_ele_exists(loc.play_loc):
            height, width = d_one.window_size()
            self.click_point(1500,700,"点击屏幕中心")
        self.click_element(loc.play_loc, "播放器页面_点击播放/暂停")
    def click_pause(self):
        """点击播放器页面，暂停播放"""
        self.click_point(0.5, 0.5, "点击屏幕中心")
        self.click_point(0.5, 0.5, "点击屏幕中心")


    def click_back(self):
        """点击播放器页面，点击播放器返回按钮，退出播放"""
        if not self.judge_ele_exists(loc.back_loc):
            self.click_point(1500, 700, "点击屏幕中心")
            # self.click_point(0.5, 0.5, "点击屏幕中心")
        self.click_element(loc.back_loc, "播放器页面_返回")

    def click_home(self):
        if device_type == "A1Back":
            # 从底部上划唤起快捷菜单
            try:
                eval(self.d).swipe(1400, 1600, 1400, 1400, 0.2)
                time.sleep(0.5)
                while not d_one(resourceId="com.zeekr.launcher.rear:id/window_navigation_home").exists:
                    eval(self.d).swipe(1400, 1600, 1400, 1400, 0.2)
                    break
                do_log.info("唤起快捷菜单成功！")
                # 点击快捷菜单的Home按钮
                time.sleep(0.4)
                eval(self.d).click(1155, 1488)
                do_log.info("点击正下方主页按钮成功")

            except:
                # 若点击Home按钮失败，则使用adb指令返回桌面
                os.system("adb shell input keyevent 3")
        else:
            height, width = d_one.window_size()
            # 1600 2560
            # 这里是横屏，所以反向
            if not self.judge_ele_exists(loc.back_loc):
                self.click_point(1500, 700, "点击屏幕中心")

                # self.click_point(0.5, 0.5, "点击屏幕中心")
            time.sleep(1)
            d_one.click(width * 0.02, height * 0.94)
            do_log.info("点击左下角的首页按钮")


    def awake_player_menu(self):
        time.sleep(0.5)
        """点击屏幕唤起播放器菜单"""
        if not self.judge_ele_exists(loc.back_loc):
            self.click_point(0.5, 0.5, "点击屏幕中心")
        do_log.info("点击屏幕唤起播放器菜单")
    def click_seek(self,x,y):
        """点击屏幕唤起播放器菜单"""
        if not self.judge_ele_exists(loc.back_loc):
            self.click_point(0.5, 0.5, "点击屏幕中心")
        do_log.info("点击屏幕唤起播放器菜单")
        time.sleep(1)
        self.click_point(x,y,"手动seek")

    def long_seek_seekbar(self,sx,ex):
        if device_type == "A1Back":
            sy,ey=1374,1374
        else:
            sy, ey = 1243, 1243

        self.click_point(0.5, 0.5, "点击屏幕中心")
        time.sleep(0.5)
        self.click_long_point(sx, sy, ex, ey, "点击拖动进度条",during=2)
        do_log.info("点击进度条后拖动进度条")
    def long_seek(self,sx,sy,ex,ey):

        self.click_point(0.5, 0.5, "点击屏幕中心")
        time.sleep(0.5)
        do_log.info("点击屏幕唤起播放器菜单")
        self.click_long_point(sx, sy, ex, ey, "点击拖动进度条")


    def click_target_schedule(self, target_time):
        # 废弃，点不准
        max_time = self.get_text(loc.maxtime_loc, "播放器页面_获取影片的总时长")
        current_seconds = time_to_seconds(target_time)
        total_seconds = time_to_seconds(max_time)
        ratio = current_seconds / total_seconds
        print(ratio)
        seek_bounds = self.get_element_attribute(loc.seekbar_loc, "bounds", "播放器页面_获取进度条的坐标尺寸")
        lx, ly, rx, ry = seek_bounds['left'], seek_bounds['top'], seek_bounds['right'], seek_bounds['bottom']
        print(lx, ly, rx, ry)
        # "290 1543 2590 1588"
        seek_center_x, seek_center_y = self.get_ele_center(loc.seekbar_loc, "播放器页面_获取进度条中心位置坐标")
        width = rx - lx
        click_x = lx + width * ratio
        click_y = seek_center_y
        self.click_point(click_x, click_y, "播放器页面_点击进度条坐标{} {}".format(click_x, click_y))

    def seek_to_target(self, target_time, compensate=0):
        """语音跳转到指定播放时间"""
        target_seconds = time_to_seconds(target_time)
        if app_version=="1.0":
            d_one_device.shell(
            "am start -a android.intent.action.VIEW -d 'iqiyi://com.qiyi.video.iv/driver?command=seek&param={}'".format(
                (target_seconds + compensate) * 1000))
        if app_version == "3.0":
            d_one_device.shell(
                "am broadcast -a com.arcvideo.car.DevCarControl  --es arc_link_type  seek  --el param {}".format(
                    (target_seconds + compensate) * 1000))
        do_log.info(f"通过广播指令将播放器跳转到 {seconds_to_time(target_seconds + compensate)}")
    def pause_by_vioce(self):
        """语音暂停"""
        d_one_device.shell(
            "am start -a android.intent.action.VIEW -d 'iqiyi://com.qiyi.video.iv/driver?command=pause'")
        do_log.info(f"通过广播指令将播放器暂停播放")
    def back_by_voice(self):
        """语音返回"""
        d_one_device.shell(
            "am start -a android.intent.action.VIEW -d 'iqiyi://com.qiyi.video.iv/driver?command=back'")
        do_log.info(f"通过广播指令将播放器退出播放")

    def open_video_by_SCHEME(self, qipuId, albumId=0, channelId=1):

        self.open_SCHEME_url(
            f"iqiyi://com.qiyi.video.iv/driver?command=play_card_video&qipuId={qipuId}&albumId={albumId}&channelId={channelId}")

    def swipe_by_adb(self, duration):
        d_one_device.shell(f"input swipe 500 800 2500 800 {duration}")
        do_log.info("通过adb命令进行屏幕seek")

    def click_air_conditioner_loc(self):
        try:
            eval(self.d).swipe(1400, 1600, 1400, 1400,0.2)
            do_log.info("点击 {} 坐标点1400, 1600, 1400, 1400成功！")
            time.sleep(0.5)
            # d_one(resourceId = "com.zeekr.launcher.rear:id/window_navigation_hvac").click()
            eval(self.d).click(1732, 1482)
            do_log.info("点击正下方空调按钮成功")

        except:
            do_log.exception("点击 {} 坐标点{},{},{},{}失败！")
            self.save_img("上滑失败")
            raise
    def click_back_loc(self):
        try:
            eval(self.d).swipe(1400, 1600, 1400, 1400,0.2)
            do_log.info("点击 {} 坐标点1400, 1600, 1400, 1400成功！")
            time.sleep(0.3)
            d_one(resourceId="com.zeekr.launcher.rear:id/window_navigation_back").click()
            do_log.info("点击正下方返回按钮成功")

        except:
            do_log.exception("点击 {} 坐标点{},{},{},{}失败！")
            self.save_img("上滑失败")
            raise
    def click_left_loc(self):
        try:
            eval(self.d).swipe(1400, 1600, 1400, 1400,0.2)
            do_log.info("点击 {} 坐标点1400, 1600, 1400, 1400成功！")
            time.sleep(0.3)
            d_one(resourceId="com.zeekr.launcher.rear:id/window_navigation_one_screen").click()
            do_log.info("点击正下方侧边按钮成功")

        except:
            do_log.exception("点击 {} 坐标点{},{},{},{}失败！")
            self.save_img("上滑失败")
            raise
    def click_home_loc(self):
        # 从底部上划唤起快捷菜单
        try:
            eval(self.d).swipe(1400, 1600, 1400, 1400,0.2)
            # time.sleep(1)
            while not d_one(resourceId = "com.zeekr.launcher.rear:id/window_navigation_home").exists:
                eval(self.d).swipe(1400, 1600, 1400, 1400, 0.2)
                break
            do_log.info("唤起快捷菜单成功！")
        # 点击快捷菜单的Home按钮
            time.sleep(0.4)
            eval(self.d).click(1155, 1488)
            do_log.info("点击正下方主页按钮成功")

        except:
        # 若点击Home按钮失败，则使用adb指令返回桌面
            os.system("adb shell input keyevent 3")
            # do_log.exception("点击 {} 坐标点{},{},{},{}失败！")
            # self.save_img("上滑失败")
            # raise




    def click_car(self):
        height, width = d_one.window_size()
        # 1600 2560
        # 这里是横屏，所以反向
        d_one.click(width * 0.5, height * 0.5)
        time.sleep(1)
        d_one.click(width * 0.101, height * 0.95)
        do_log.info("车机下方中控设置_点击车机设置(汽车图标)")
    def click_IQYI(self):
        height, width = d_one.window_size()
        d_one.click(width * 0.02, height * 0.94)
        do_log.info("点击左下角的首页按钮")
        time.sleep(1)
        d_one.click(2298, 1535)
        do_log.info("点击应用按钮")
        time.sleep(1)
        d_one.click(200, 600)
        do_log.info("点击爱奇艺按钮")

    def click_card(self):
        if device_type == "A1Back":
            try:
                eval(self.d).swipe(0, 610, 300, 610,0.2)
                # time.sleep(3)
                while not d_one(resourceId = "com.zeekr.launcher.rear:id/media_open_app", text = "恢复播放").exists:
                    eval(self.d).swipe(0, 610, 300, 610, 0.2)
                    do_log.info("左滑成功！")
                    break
                time.sleep(1)
                eval(self.d).click(917, 320)
                do_log.info("点击卡片成功")
            except:
                do_log.exception("点击 {} 坐标点{},{},{},{}失败！")
                self.save_img("左滑失败")
                raise
        else:
            height, width = d_one.window_size()
            d_one.click(width * 0.02, height * 0.94)
            do_log.info("点击左下角的首页按钮")
            time.sleep(1)
            d_one.click(2298, 1535)
            do_log.info("点击应用按钮")
            time.sleep(1)
            d_one.click(200, 600)
            do_log.info("点击爱奇艺按钮")







if __name__ == '__main__':
    do_playpage = PlayerPage(device="d_one")
    do_mainpage = MainPage(device="d_one")  # 进入极氪影院
    # do_playpage.seek_to_target("00:36:17")
    # time.sleep(10)
    # do_playpage.long_seek_seekbar(1300, 1374, 2400, 1374)
    # do_playpage.click_home_loc()
    # time.sleep(3)
    do_playpage.click_play()
    pass
